package com.hspedu.collection_;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/2/6
 * @time 18:16
 */
public class ListExercise02 {
    public static void main(String[] args) {
        List list = new ArrayList();

        list.add(new Book("红楼梦", "曹雪芹", 100));
        list.add(new Book("西游记", "吴承恩", 10));
        list.add(new Book("水浒传", "施耐庵", 19));
        list.add(new Book("三国志", "罗贯中", 80));

        List sortedList = sort(list);
        for (Object book : sortedList) {
            System.out.print(book);
        }

    }

    public static List sort(List list){
        for (int i = 1 ; i <= list.size() - 1 ; i++){
            for (int j = 0; j < list.size() - i ; j++) {
                Book book1 = (Book) list.get(j);
                Book book2 = (Book) list.get(j + 1);

                if (book1.getPrice() > book2.getPrice()){
                    //这里不用引入中间变量
                    //画图想一下，改变一下数组中每个元素的指向
                    //数组中的每个元素其实都是指向new出来的Book对象
                    list.set(j,book2);
                    list.set(j+1,book1);
                }

            }
        }

        return list;
    }
}
